package com.qzsoft.zhjd.server.modules.ludong.asphalt.handler;

import java.math.BigDecimal;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;

import com.qzsoft.zhjd.server.modules.asphalt.entity.CollectAsphaltAlarmEntity;
import com.qzsoft.zhjd.server.modules.asphalt.entity.CollectAsphaltDataEntity;
import com.qzsoft.zhjd.server.modules.asphalt.entity.CollectAsphaltDataRatioEntity;
import com.qzsoft.zhjd.server.modules.asphalt.entity.CollectAsphaltDataSieveEntity;
import com.qzsoft.zhjd.server.modules.asphalt.entity.CollectAsphaltDataWeightEntity;
import com.qzsoft.zhjd.server.modules.asphalt.entity.CollectAsphaltMatchColdEntity;
import com.qzsoft.zhjd.server.modules.asphalt.entity.CollectAsphaltMatchEntity;
import com.qzsoft.zhjd.server.modules.asphalt.entity.CollectAsphaltMatchHotEntity;
import com.qzsoft.zhjd.server.modules.asphalt.entity.CollectAsphaltMatchThresholdEntity;
import com.qzsoft.zhjd.server.modules.asphalt.handler.AsphaltAlarmHandler;
import com.qzsoft.zhjd.server.modules.asphalt.handler.AsphaltDataHandler;
import com.qzsoft.zhjd.server.modules.asphalt.handler.AsphaltDataRatioHandler;
import com.qzsoft.zhjd.server.modules.asphalt.handler.AsphaltDataSieveHandler;
import com.qzsoft.zhjd.server.modules.asphalt.handler.AsphaltDataWeightHandler;
import com.qzsoft.zhjd.server.modules.asphalt.mapper.CollectAsphaltAlarmMapper;
import com.qzsoft.zhjd.server.modules.asphalt.mapper.CollectAsphaltDataMapper;
import com.qzsoft.zhjd.server.modules.asphalt.mapper.CollectAsphaltDataRatioMapper;
import com.qzsoft.zhjd.server.modules.asphalt.mapper.CollectAsphaltDataSieveMapper;
import com.qzsoft.zhjd.server.modules.asphalt.mapper.CollectAsphaltDataWeightMapper;
import com.qzsoft.zhjd.server.modules.asphalt.model.CollectDataModel;
import com.qzsoft.zhjd.server.modules.asphalt.service.CollectAsphaltMatchColdService;
import com.qzsoft.zhjd.server.modules.asphalt.service.CollectAsphaltMatchHotService;
import com.qzsoft.zhjd.server.modules.asphalt.service.CollectAsphaltMatchService;
import com.qzsoft.zhjd.server.modules.asphalt.service.CollectAsphaltMatchThresholdService;
import com.qzsoft.zhjd.server.modules.asphalt.service.CollectAsphaltMatchTypeService;
import com.qzsoft.zhjd.server.modules.ludong.asphalt.entity.AsphaltConcreteCollectionEntity;

@Component
public class LudongAsphaltHandler {

    @Autowired
    private CollectAsphaltMatchService collectAsphaltMatchService;

    @Autowired
    private CollectAsphaltMatchTypeService collectAsphaltMatchTypeService;

    @Autowired
    private CollectAsphaltMatchHotService collectAsphaltMatchHotService;

    @Autowired
    private CollectAsphaltMatchColdService collectAsphaltMatchColdService;

    @Autowired
    private CollectAsphaltMatchThresholdService collectAsphaltMatchThresholdService;

    @Autowired
    private CollectAsphaltDataMapper collectAsphaltDataMapper;

    @Autowired
    private CollectAsphaltAlarmMapper collectAsphaltAlarmMapper;

    @Autowired
    private CollectAsphaltDataSieveMapper collectAsphaltDataSieveMapper;

    @Autowired
    private CollectAsphaltDataWeightMapper collectAsphaltDataWeightMapper;

    @Autowired
    private CollectAsphaltDataRatioMapper collectAsphaltDataRatioMapper;

    @Async
    public void insert(List<AsphaltConcreteCollectionEntity> list, String matchCode, String stationCode) {

        // 获取配方信息
        CollectAsphaltMatchEntity match = collectAsphaltMatchService.getByStationAndCode(stationCode, matchCode);

        // 获取热料配置信息
        List<CollectAsphaltMatchHotEntity> hots = null;
        // 获取上下限信息
        CollectAsphaltMatchThresholdEntity threshold = null;
        // 获取冷料配比
        CollectAsphaltMatchColdEntity cold = null;
        // 获取筛孔列表
        Set<String> sieveSet = null;
        if (null != match) {
            hots = collectAsphaltMatchHotService.listByMatchId(match.getId());
            threshold = collectAsphaltMatchThresholdService.getByTypeAndName(match.getMatchType(), match.getMatchName());
            cold = collectAsphaltMatchColdService.getById(match.getId());
            sieveSet = collectAsphaltMatchTypeService.getSieveSetByType(match.getMatchType());
        }

        CollectDataModel model = null;
        AsphaltConcreteCollectionEntity data;
        for (int i = 0, len = list.size(); i < len; i++) {
            data = list.get(i);

            model = new CollectDataModel();
            model.setId(data.getId());
            model.setDischargeTime(data.getDischargingTime());
            model.setMatchCode(matchCode);
            model.setStationCode(stationCode);
            model.setMixingDuration(strToInt(data.getMixingDuration()));
            model.setDischargeTemp(strToBigDecimal(data.getTemperature()));
            model.setAsphaltTemp(strToBigDecimal(data.getAsphaltTemp()));
            model.setSluiceTemp(strToBigDecimal(data.getSluiceTemp()));
            model.setBatchWeight(strToBigDecimal(data.getBatchWeight()));
            model.setGravel1Act(data.getSand1Act());
            model.setGravel2Act(data.getSand2Act());
            model.setGravel3Act(data.getGravel1Act());
            model.setGravel4Act(data.getGravel2Act());
            model.setGravel5Act(data.getGravel3Act());
            model.setGravel6Act(data.getGravel4Act());
            model.setPowder1Act(data.getSlagPowderAct());
            model.setAsphaltAct(data.getAsphaltAct());
            model.setRecycledMaterialAct(data.getRecycledMaterialAct());
            model.setGravel1Theo(data.getSand1Theo());
            model.setGravel2Theo(data.getSand2Theo());
            model.setGravel3Theo(data.getGravel1Theo());
            model.setGravel4Theo(data.getGravel2Theo());
            model.setGravel5Theo(data.getGravel3Theo());
            model.setGravel6Theo(data.getGravel4Theo());
            model.setPowder1Theo(data.getSlagPowderTheo());
            model.setAsphaltTheo(data.getAsphaltTheo());
            model.setRecycledMaterialTheo(data.getRecycledMaterialTheo());
            handler(model, match, hots, threshold, cold, sieveSet);
        }
    }

    @Async
    public void insert(AsphaltConcreteCollectionEntity data, String stationCode) {

        // 获取配方信息
        String matchCode = data.getProportionIdGet();
        CollectAsphaltMatchEntity match = collectAsphaltMatchService.getByStationAndCode(stationCode, matchCode);

        // 获取热料配置信息
        List<CollectAsphaltMatchHotEntity> hots = null;
        // 获取上下限信息
        CollectAsphaltMatchThresholdEntity threshold = null;
        // 获取冷料配比
        CollectAsphaltMatchColdEntity cold = null;
        // 获取筛孔列表
        Set<String> sieveSet = null;
        if (null != match) {
            hots = collectAsphaltMatchHotService.listByMatchId(match.getId());
            threshold = collectAsphaltMatchThresholdService.getByTypeAndName(match.getMatchType(), match.getMatchName());
            cold = collectAsphaltMatchColdService.getById(match.getId());
            sieveSet = collectAsphaltMatchTypeService.getSieveSetByType(match.getMatchType());
        }

        CollectDataModel model = new CollectDataModel();
        model.setId(data.getId());
        model.setDischargeTime(data.getDischargingTime());
        model.setMatchCode(matchCode);
        model.setStationCode(stationCode);
        model.setMixingDuration(strToInt(data.getMixingDuration()));
        model.setDischargeTemp(strToBigDecimal(data.getTemperature()));
        model.setAsphaltTemp(strToBigDecimal(data.getAsphaltTemp()));
        model.setSluiceTemp(strToBigDecimal(data.getSluiceTemp()));
        model.setBatchWeight(strToBigDecimal(data.getBatchWeight()));
        model.setGravel1Act(data.getSand1Act());
        model.setGravel2Act(data.getSand2Act());
        model.setGravel3Act(data.getGravel1Act());
        model.setGravel4Act(data.getGravel2Act());
        model.setGravel5Act(data.getGravel3Act());
        model.setGravel6Act(data.getGravel4Act());
        model.setPowder1Act(data.getSlagPowderAct());
        model.setAsphaltAct(data.getAsphaltAct());
        model.setRecycledMaterialAct(data.getRecycledMaterialAct());
        model.setGravel1Theo(data.getSand1Theo());
        model.setGravel2Theo(data.getSand2Theo());
        model.setGravel3Theo(data.getGravel1Theo());
        model.setGravel4Theo(data.getGravel2Theo());
        model.setGravel5Theo(data.getGravel3Theo());
        model.setGravel6Theo(data.getGravel4Theo());
        model.setPowder1Theo(data.getSlagPowderTheo());
        model.setAsphaltTheo(data.getAsphaltTheo());
        model.setRecycledMaterialTheo(data.getRecycledMaterialTheo());
        handler(model, match, hots, threshold, cold, sieveSet);
    }

    @Transactional(rollbackFor = Exception.class)
    public void handler(CollectDataModel model, CollectAsphaltMatchEntity match, List<CollectAsphaltMatchHotEntity> hots,
                        CollectAsphaltMatchThresholdEntity threshold, CollectAsphaltMatchColdEntity cold, Set<String> sieveSet) {
        // 删除已经存在的数据
        String originalId = model.getId();
        deleteByOriginalId(originalId);

        // 数据主键
        String id = UUID.randomUUID().toString().replace("-", "");

        // 处理生产数据重量表
        CollectAsphaltDataWeightEntity weightData = AsphaltDataWeightHandler.coverTo(model, match, cold);
        weightData.setId(id);

        // 处理生产数据占比表
        CollectAsphaltDataRatioEntity ratioData = AsphaltDataRatioHandler.coverTo(weightData);
        ratioData.setId(id);

        // 处理筛孔数据
        CollectAsphaltDataSieveEntity sieveData = AsphaltDataSieveHandler.coverTo(weightData, ratioData, hots, sieveSet);
        sieveData.setId(id);

        // 处理生产数据主表
        CollectAsphaltDataEntity data = AsphaltDataHandler.coverToData(model, match);
        data.setId(id);
        data.setAsphaltAggregateRatio(ratioData.getAsphaltRatioW());

        // 处理预警数据
        CollectAsphaltAlarmEntity alarm = AsphaltAlarmHandler.coverTo(data, sieveData, match, threshold);
        alarm.setId(id);

        // 执行添加操作
        collectAsphaltDataMapper.insert(data);
        collectAsphaltDataSieveMapper.insert(sieveData);
        collectAsphaltDataWeightMapper.insert(weightData);
        collectAsphaltDataRatioMapper.insert(ratioData);
        collectAsphaltAlarmMapper.insert(alarm);
    }

    /**
     * @Title deleteByOriginalId
     * @Description 根据原始主键删除已经存在的数据
     * @param originalId 原始主键
     */
    private void deleteByOriginalId(String originalId) {
        // 如果原始主键为空，不做处理
        if (ObjectUtils.isEmpty(originalId)) {
            return;
        }

        // 使用原始主键查询数据
        QueryWrapper<CollectAsphaltDataEntity> queryWrapper = new QueryWrapper<CollectAsphaltDataEntity>();
        queryWrapper.eq("original_id", originalId);
        List<CollectAsphaltDataEntity> list = collectAsphaltDataMapper.selectList(queryWrapper);
        if (null == list || 0 == list.size()) {
            return;
        }

        // 删除已经存在的数据
        String id = list.get(0).getId();
        collectAsphaltDataMapper.deleteById(id);
        collectAsphaltDataSieveMapper.deleteById(id);
        collectAsphaltDataWeightMapper.deleteById(id);
        collectAsphaltDataRatioMapper.deleteById(id);
        collectAsphaltAlarmMapper.deleteById(id);
    }

    private Integer strToInt(String str) {
        if (null != str) {
            try {
                return Integer.parseInt(str);
            } catch (Exception e) {
            }
        }
        return null;
    }

    private BigDecimal strToBigDecimal(String str) {
        if (null != str) {
            try {
                return new BigDecimal(str);
            } catch (Exception e) {
            }
        }
        return null;
    }

}
